package com.cswnode.demo.util;

import com.alibaba.fastjson.JSONObject;
import com.cswnode.demo.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.DigestUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

/**
 * @author csw
 * @create 2021/1/28 11:43
 */

public class Utils {
    private Utils(){}

    /**
     * 生成随机字符串
     * @return 生成的uuid
     */
    public static String GetUUID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    /**
     * md5加密
     * @param key
     * @return
     */
    public static String MD5(String key){
        if (StringUtils.isBlank(key)){
            return null;
        }
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }

    /**
     * 获得当前登录用户
     * @return 当前登录用户
     */
    public static User getLoginUser(){
        return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public static Long getLoginUserId(){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user == null){
            return null;
        }
        return user.getUserId();
    }

    public static String getLoginUserName(){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user == null){
            return null;
        }
        return user.getUserNameCn();
    }

    public static String getJsonString(int code, String msg, Map<String,Object> map){
        JSONObject json = new JSONObject();
        json.put("code",code);
        json.put("msg",msg);
        if (map != null){
            //遍历map中的key
            for (String key : map.keySet()){
                json.put(key,map.get(key));
            }
        }
        return json.toJSONString();
    }

    public static String getJsonString(int code, String msg){
        return getJsonString(code,msg,null);
    }

    public static String getJsonString(int code){
        return getJsonString(code,null,null);
    }

    public static String getValue(HttpServletRequest request, String name){
        if (request == null && name == null){
            throw new IllegalArgumentException("参数为空！");
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }


}
